package com.lcn.filter;

import com.lcn.base.BaseInfoProperties;
import com.lcn.config.ExcludePathConfig;
import com.lcn.grace.result.ResponseStatusEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.RequestPath;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class ExcludePathFilter extends BaseInfoProperties implements GlobalFilter, Ordered {

    @Resource
    private ExcludePathConfig excludePathConfig;

    private AntPathMatcher matchesPattern = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求路径
        String requestPath = exchange.getRequest().getURI().getPath();
        for (String path : excludePathConfig.getPaths()) {
            if (matchesPattern.matchStart(path, requestPath)) {
                log.info("路径{}被放行", requestPath);
                return chain.filter(exchange);
            }
        }
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String userId = headers.getFirst("headerUserId");
        String token = headers.getFirst("headerUserToken");
        if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(token)) {
            // 单设备登陆
//            String redisToken = redis.get(REDIS_USER_TOKEN + ":" + userId);
//            if (StringUtils.isNotBlank(redisToken) && redisToken.equals(token)) {
//                log.info("{}校验通过，放行", requestPath);
//                return chain.filter(exchange);
//            }
            // 多设备登录
            String redisUserId = redis.get(REDIS_USER_TOKEN + ":" + token);
            if (StringUtils.isNotBlank(redisUserId) && redisUserId.equals(userId)) {
                log.info("{}校验通过，放行", requestPath);
                return chain.filter(exchange);
            }
        }
        log.info("未登录，路径{}被拦截", requestPath);
        return RenderErrorUtil.renderErrorMsg(exchange, ResponseStatusEnum.UN_LOGIN);
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
